package com.taskinception.utils;

import android.util.Log;

import com.taskinception.TIApplication;
import com.taskinception.model.Task;

/**
 * Class with utilities for work with tasks.
 * 
 * @author Jan Svehla
 */
public class TaskUtils {

	/**
	 * Merges all task in two provided task trees.
	 * For every child task it tries to find task with same remoteID
	 * between children of old task. If found, mergeTasks is called which
	 * takes care of updating the task. If it was not found, new task with
	 * it's children is inserted into old task's children.
	 * 
	 * @param newTask New Task tree to be merged.
	 * @param oldTask Original Task tree.
	 */
	public static void mergeTaskTrees(Task newTask, Task oldTask) {
		if (newTask.getId() != 0 || oldTask.getId() != 0) {
			Log.e("TaskUtils", "mergeTaskTrees: merging non-root tasks: " + newTask.getId() + " " + oldTask.getId());
		}
		
		for (Task newChildTask : newTask.getChildren()) {
			Log.e("TaskUtils", "mergeTaskTrees: newChildTask: " + newChildTask.getTitle() + " " + newChildTask.getRemoteId() + " oldTask: " + oldTask.getTitle() + " " + oldTask.getRemoteId());
			Task oldChildTask = oldTask.findChildWithRemoteId(newChildTask);
			if (oldChildTask != null) {
				Log.e("TaskUtils", "mergeTaskTrees: newTask: " + newTask.getTitle() + " merging");
				mergeTasks(newChildTask, oldChildTask);
			} else {
				Log.e("TaskUtils", "mergeTaskTrees: newTask: " + newTask.getTitle() + " creating new");
				TIApplication.getInstance().insertTaskWithChildrenIntoTaskTree(newChildTask, oldTask.getId());
			}
		}
	}

	/**
	 * Checks if remoteIDs of task are equal. If yes and if received task's
	 * last modified date is later than the old one, old task is updated.
	 * It also recursively merges children tasks.
	 * @param newTask
	 * @param oldTask
	 */
	private static void mergeTasks(Task newTask, Task oldTask) {
		Log.d("TaskUtils", "Merging tasks: " + newTask.getTitle() + " " + oldTask.getTitle());
		if (newTask.getLastModifiedDate() > oldTask.getLastModifiedDate()) {
			TIApplication.getInstance().updateTaskInTaskTree(newTask, oldTask.getId());
			for (Task newChildTask : newTask.getChildren()) {
				Task oldChildTask = oldTask.findChildWithRemoteId(newChildTask);
				if (oldChildTask != null) {
					mergeTasks(newChildTask, oldChildTask);
				} else {
					TIApplication.getInstance().insertTaskWithChildrenIntoTaskTree(newChildTask, oldTask.getId());
				}
			}
		}
	}

	/**
	 * Checkes if remoteIDs equal
	 * @param t1 task1
	 * @param t2 task2
	 * @return equality...
	 */
	private static boolean equalRemoteId(Task t1, Task t2) {
		if (t1.getOwner().equals(t2.getOwner())) {
			if (t1.getRemoteId() == t2.getRemoteId()) {
				return true;
			}
		}
		return false;
	}
}
